// ignore_for_file: unused_field, unused_element, avoid_print, deprecated_member_use

import 'dart:io';
import 'dart:math';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:http/http.dart' as http;
import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:tencent_calls_uikit/tencent_calls_uikit.dart';
import 'package:tencent_chat_i18n_tool/tencent_chat_i18n_tool.dart';
import 'package:tencent_cloud_chat_demo/config.dart';
import 'package:tencent_cloud_chat_demo/db/custom_sticker.dart';
import 'package:tencent_cloud_chat_demo/db/custom_sticker_entity.dart';
import 'package:tencent_cloud_chat_demo/src/group_application_list.dart';
import 'package:tencent_cloud_chat_demo/src/group_profile.dart';
import 'package:tencent_cloud_chat_demo/src/provider/custom_sticker_package.dart';
import 'package:tencent_cloud_chat_demo/src/provider/local_setting.dart';
import 'package:tencent_cloud_chat_demo/src/provider/theme.dart';
import 'package:tencent_cloud_chat_demo/src/search.dart';
import 'package:tencent_cloud_chat_demo/src/tencent_page.dart';
import 'package:tencent_cloud_chat_demo/src/user_profile.dart';
import 'package:tencent_cloud_chat_demo/utils/api/sticker.dart';
import 'package:tencent_cloud_chat_demo/utils/commonUtils.dart';
import 'package:tencent_cloud_chat_demo/utils/custom_message/calling_message/calling_message_data_provider.dart';
import 'package:tencent_cloud_chat_demo/utils/custom_message/custom_message_element.dart';
import 'package:tencent_cloud_chat_demo/utils/pateform.dart';
import 'package:tencent_cloud_chat_demo/utils/path.dart';
import 'package:tencent_cloud_chat_demo/utils/picture.dart';
import 'package:tencent_cloud_chat_demo/utils/toast.dart';
import 'package:tencent_cloud_chat_sdk/enum/group_type.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/enum/offlinePushInfo.dart';
import 'package:tencent_cloud_chat_sdk/manager/v2_tim_manager.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_friend_info.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/life_cycle/chat_life_cycle.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_chat_global_model.dart';
import 'package:tencent_cloud_chat_uikit/data_services/core/tim_uikit_wide_modal_operation_key.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/theme/color.dart';
import 'package:tencent_cloud_chat_uikit/theme/tui_theme.dart';
import 'package:tencent_cloud_chat_uikit/ui/controller/tim_uikit_chat_controller.dart';
import 'package:tencent_cloud_chat_uikit/ui/controller/tim_uikit_conversation_controller.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/message.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/permission.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/platform.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/screen_utils.dart';
import 'package:tencent_cloud_chat_uikit/ui/views/TIMUIKitChat/TIMUIKitTextField/tim_uikit_text_field_layout/wide.dart';
import 'package:tencent_cloud_chat_uikit/ui/views/TIMUIKitProfile/profile_widget.dart';
import 'package:tencent_cloud_chat_uikit/ui/views/TIMUIKitProfile/widget/tim_uikit_profile_widget.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/link_preview/common/utils.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/wide_popup.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'widgets/customStickerPannel/custom_sticker_pannel.dart';
import 'package:tencent_super_tooltip/tencent_super_tooltip.dart';

class Chat extends StatefulWidget {
  final V2TimConversation selectedConversation;
  final V2TimMessage? initFindingMsg;
  final VoidCallback? showGroupProfile;
  final ValueChanged<V2TimConversation>? directToChat;

  const Chat(
      {Key? key,
      required this.selectedConversation,
      this.initFindingMsg,
      this.showGroupProfile,
      this.directToChat})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _ChatState();
}

class _ChatState extends State<Chat> {
  final TIMUIKitChatController _chatController = TIMUIKitChatController();
  late TIMUIKitConversationController _controller;
  String? backRemark;
  final V2TIMManager sdkInstance = TIMUIKitCore.getSDKInstance();
  String? conversationName;
  String? customerServiceTyping;
  bool canSendEvaluate = false;
  String? myFaceUrl;
  SuperTooltip? tooltip;
  TUICallKit? _calling;

  String _getTitle() {
    return backRemark ?? widget.selectedConversation.showName ?? "Chat";
  }

  String? _getConvID() {
    return widget.selectedConversation.type == 1
        ? widget.selectedConversation.userID
        : widget.selectedConversation.groupID;
  }

  ConvType _getConvType() {
    return widget.selectedConversation.type == 1
        ? ConvType.c2c
        : ConvType.group;
  }

  final chatTooltip = [
    {
      "id": "createConv1",
      "asset": "assets/c2c_conv.png", // 对应 "查看好友信息"
      "label": TIM_t("查看好友信息")
    },
    {
      "id": "audioCall",
      "asset": "assets/group_conv.png", // 对应 "语音通话"
      "label": TIM_t("语音通话")
    },
    {
      "id": "videoCall",
      "asset": "assets/group_conv.png", // 对应 "视频通话"
      "label": TIM_t("视频通话")
    },
  ];

  List<Widget> _getTooltipContent(BuildContext context) {
    List toolTipList = chatTooltip;

    // 新增逻辑：当 userID 为 "zml20" 时，移除 "查看好友信息"
    if (widget.selectedConversation.userID == "zml20") {
      toolTipList = toolTipList.where((e) => e["id"] != "createConv1").toList();
    }

    return toolTipList.map((e) {
      return InkWell(
        onTap: () {
          _handleTapTooltipItem(e["id"]!);
          tooltip!.close();
        },
        child: Row(
          children: [
            // Image.asset(
            //   e["asset"]!,
            //   width: 21,
            //   height: 21,
            // ),
            // const SizedBox(
            //   width: 4,
            // ),
            Text(e['label']!)
          ],
        ),
      );
    }).toList();
  }

  _handleTapTooltipItem(String id) async {
    switch (id) {
      case "createConv1":
        final userID = widget.selectedConversation.userID;
        if (userID == 'zml20') {
          return;
        }
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) => UserProfile(
              userID: userID!,
              onRemarkUpdate: (String newRemark) {
                setState(() {
                  conversationName = newRemark;
                });
              },
            ),
          ),
        );
        break;

      case "audioCall":
        debugPrint("语音通话");

        OfflinePushInfo offlinePush = OfflinePushInfo(
          title: "",
          desc: TIM_t("邀请你语音通话"),
          ext: "{\"conversationID\": \"\"}",
          disablePush: false,
          ignoreIOSBadge: false,
        );

        await Permissions.checkPermission(context, Permission.microphone.value);
        TUIOfflinePushInfo tuiOfflinePushInfo =
            CommonUtils.convertTUIOfflinePushInfo(offlinePush);
        TUICallParams params = TUICallParams();
        params.offlinePushInfo = tuiOfflinePushInfo;
        if (widget.selectedConversation.userID != null) {
          await _calling?.call(widget.selectedConversation.userID!,
              TUICallMediaType.audio, params);
        } else {
          debugPrint("User ID is null, cannot make the call.");
        }
        break;

      case "videoCall":
        debugPrint("视频通话");
        OfflinePushInfo offlinePush = OfflinePushInfo(
          title: "",
          desc: TIM_t("邀请你视频通话"),
          ext: "{\"conversationID\": \"\"}",
          disablePush: false,
          ignoreIOSBadge: false,
        );

        await Permissions.checkPermission(context, Permission.camera.value);
        await Permissions.checkPermission(context, Permission.microphone.value);
        TUIOfflinePushInfo tuiOfflinePushInfo =
            CommonUtils.convertTUIOfflinePushInfo(offlinePush);
        TUICallParams params = TUICallParams();
        params.offlinePushInfo = tuiOfflinePushInfo;
        if (widget.selectedConversation.userID != null) {
          _calling?.call(widget.selectedConversation.userID!,
              TUICallMediaType.video, params);
        } else {
          debugPrint("User ID is null, cannot make the call.");
        }
        break;
    }
  }

  void _handleOnConvItemTapedWithPlace(V2TimConversation? selectedConv,
      [V2TimMessage? toMessage]) async {
    await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => Chat(
            selectedConversation: selectedConv!,
            initFindingMsg: toMessage,
          ),
        ));
    _controller.reloadData();
  }

  _showTooltip(BuildContext context) {
    tooltip = SuperTooltip(
        minimumOutSidePadding: 5,
        arrowTipDistance: 15,
        arrowBaseWidth: 15.0,
        arrowLength: 10.0,
        // maxHeight: 110,
        // maxWidth: 110,
        borderColor: Colors.white,
        backgroundColor: Colors.white,
        shadowColor: Colors.black26,
        content: Wrap(
          direction: Axis.vertical,
          spacing: 10,
          children: [..._getTooltipContent(context)],
        ),
        popupDirection: TooltipDirection.down);
    tooltip?.show(context);
  }

  void _onTapAvatar(String userID, TapDownDetails tapDetails, TUITheme theme) {
    // 新增逻辑：当 userID 为 "zml20" 时，不执行任何操作
    if (widget.selectedConversation.userID == "zml20") {
      return;
    }

    final isWideScreen =
        TUIKitScreenUtils.getFormFactor(context) == DeviceType.Desktop;
    if (isWideScreen) {
      onClickUserName(
          Offset(
              min(tapDetails.globalPosition.dx,
                  MediaQuery.of(context).size.width - 350),
              min(tapDetails.globalPosition.dy,
                  MediaQuery.of(context).size.height - 490)),
          theme,
          userID);
    } else {
      if (userID == 'zml20') {
        return;
      }
      Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => UserProfile(
              userID: userID,
              onRemarkUpdate: (String newRemark) {
                setState(() {
                  conversationName = newRemark;
                });
              },
            ),
          ));
    }
  }

  @override
  void initState() {
    super.initState();
    loadStickers();
    _initTUICalling();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(Chat oldWidget) {
    super.didUpdateWidget(oldWidget);
    final isWideScreen =
        TUIKitScreenUtils.getFormFactor(context) == DeviceType.Desktop;
  }

  _initTUICalling() async {
    _calling = TUICallKit.instance;
  }

  _itemClick(String id, BuildContext context, V2TimConversation conversation,
      VoidCallback closeFunc) async {
    closeFunc();
    switch (id) {
      case "sendMsg":
        if (widget.directToChat != null) {
          widget.directToChat!(conversation);
        }
        break;
    }
  }

  _buildBottomOperationList(BuildContext context,
      V2TimConversation conversation, VoidCallback closeFunc, TUITheme theme) {
    List operationList = [
      {
        "label": TIM_t("发送消息"),
        "id": "sendMsg",
      }
    ];

    return operationList.map((e) {
      return TIMUIKitProfileWidget.wideButton(
        margin: const EdgeInsets.symmetric(vertical: 0),
        smallCardMode: true,
        onPressed: () =>
            _itemClick(e["id"] ?? "", context, conversation, closeFunc),
        text: e["label"] ?? "",
        color: theme.primaryColor ?? hexToColor("3e4b67"),
      );
    }).toList();
  }

  void onClickUserName(Offset offset, TUITheme theme, [String? user]) {
    final conversationType = widget.selectedConversation.type;
    if (conversationType == 1 || user != null) {
      final userID = user ?? widget.selectedConversation.userID;
      TUIKitWidePopup.showPopupWindow(
          operationKey: TUIKitWideModalOperationKey.showUserProfileFromChat,
          context: context,
          isDarkBackground: false,
          width: 350,
          offset: offset,
          height: (widget.selectedConversation.type == 2) ? 490 : 444,
          child: (closeFunc) => Container(
                padding: const EdgeInsets.only(top: 20, left: 10, right: 10),
                child: TIMUIKitProfile(
                  smallCardMode: true,
                  profileWidgetBuilder: ProfileWidgetBuilder(customBuilderOne:
                      (bool isFriend, V2TimFriendInfo friendInfo,
                          V2TimConversation conversation) {
                    // If you don't allow sending message when friendship not exist,
                    // please not comment the following lines.

                    // if(!isFriend){
                    //   return Container();
                    // }
                    return Column(
                        children: _buildBottomOperationList(
                            context, conversation, closeFunc, theme));
                  }),
                  profileWidgetsOrder: [
                    ProfileWidgetEnum.userInfoCard,
                    ProfileWidgetEnum.operationDivider,
                    ProfileWidgetEnum.pinConversationBar,
                    ProfileWidgetEnum.messageMute,
                    if (widget.selectedConversation.type == 2)
                      ProfileWidgetEnum.customBuilderOne,
                  ],
                  userID: userID ?? "",
                ),
              ));
    } else {
      if (widget.showGroupProfile != null) {
        widget.showGroupProfile!();
      }
    }
  }

  List<Emoji> stickerImages = [];

  Future<void> loadStickers() async {
    final result = await getAllEmojis();
    final emojiList = result.map((e) => Emoji.fromMap(e)).toList();
    setState(() {
      stickerImages = emojiList;
    });
  }

  Future<void> pickImage() async {
    await pickAndCompressWechatStyleEmoji();
    await loadStickers();
  }

  Future<void> deleteSticker(List<int> ids) async {
    CustomSitckerAPI.deleteSticker(ids.join(','));
    // 删除数据库
    for (var id in ids) {
      await deleteEmoji(id);
    }
    await loadStickers();
  }

  Widget _renderCustomStickerPanel({
    void Function()? sendTextMessage,
    void Function(int index, String data)? sendFaceMessage,
    void Function()? deleteText,
    void Function(int unicode)? addText,
    void Function(String singleEmojiName)? addCustomEmojiText,
    List<CustomEmojiFaceData>? defaultCustomEmojiStickerList,
    double? width,
    double? height,
  }) {
    final theme = Provider.of<DefaultThemeData>(context).theme;
    // _chatController.loadHistoryMessageList(count: 1);
    return CustomStickerPannel(
      userID: widget.selectedConversation.userID,
      groupID: widget.selectedConversation.groupID,
      stickerImages: stickerImages,
      pickImage: pickImage,
      deleteSticker: deleteSticker,
      chatController: _chatController,
    );
  }

  @override
  Widget build(BuildContext context) {
    final LocalSetting localSetting = Provider.of<LocalSetting>(context);
    final isWideScreen =
        TUIKitScreenUtils.getFormFactor(context) == DeviceType.Desktop;
    final theme = Provider.of<DefaultThemeData>(context).theme;
    final groupID = widget.selectedConversation.groupID;
    final groupType = widget.selectedConversation.groupType;
    List<String> notAllowGroupType = [
      GroupType.Community,
      GroupType.AVChatRoom
    ];
    bool canAddVotePlugin = false;
    if (TencentUtils.checkString(groupID) != null &&
        TencentUtils.checkString(groupType) != null &&
        !notAllowGroupType.contains(groupType)) {
      canAddVotePlugin = true;
    }
    bool isCustomerServiceChat = IMDemoConfig.customerServiceUserList
        .contains(widget.selectedConversation.userID);
    return TencentPage(
      name: 'chat',
      child: TIMUIKitChat(
        userAvatarBuilder: (context, userInfo) {
          if (userInfo.isSelf != null && userInfo.isSelf == true) {
            if (userInfo.faceUrl != null &&
                userInfo.faceUrl!.isNotEmpty &&
                (myFaceUrl == null || myFaceUrl!.isEmpty)) {
              myFaceUrl = userInfo.faceUrl;
            }
            if (myFaceUrl != null && myFaceUrl!.isNotEmpty) {
              return Image.network(
                myFaceUrl!,
                width: 40,
              );
            }
          } else {
            if (widget.selectedConversation.faceUrl != null &&
                widget.selectedConversation.faceUrl!.isNotEmpty) {
              return Image.network(
                widget.selectedConversation.faceUrl!,
                width: 40,
              );
            }
          }
          return Image.asset(
            'assets/default_avatar.png',
            width: 40,
          );
        },
        toolTipsConfig: getPlatformType() == 'Mobile'
            ? ToolTipsConfig(additionalMessageToolTips:
                (V2TimMessage b, dynamic Function() a) {
                final isMmage =
                    b.elemType == MessageElemType.V2TIM_ELEM_TYPE_IMAGE;
                if (b.isSelf != null && b.isSelf != false) {
                  return [];
                }
                if (isMmage) {
                  final cloudCustomData = b.cloudCustomData ?? '';
                  return [
                    MessageToolTipItem(
                      iconImageAsset: 'assets/sticker/collect_menu.png',
                      label: 'Add',
                      onClick: () async {
                        a();
                        // 表情下载下来
                        if (cloudCustomData.contains('custom_sticker')) {
                          final url = b.elemList.first.imageList.first.url;
                          final name = url.split('/').last.split('?').first;
                          final filePath = AppPath.resolveEmojiPath(name);
                          final file = File(filePath);
                          final response = await http.get(Uri.parse(url));
                          if (response.statusCode == 200) {
                            await file.writeAsBytes(response.bodyBytes);

                            await addSticker(file.path, name);
                            loadStickers();
                          }
                        } else {
                          // 图片就进入到裁剪
                          final url = b.elemList.first.imageList.first.url;
                          print('url $url');
                          final name = url.split('/').last.split('?').first;
                          final filePath = AppPath.resolveEmojiPath(name);
                          final file = File(filePath);
                          final response = await http.get(Uri.parse(url));
                          if (response.statusCode == 200) {
                            await file.writeAsBytes(response.bodyBytes);
                            final String fileName;
                            if (file.path.endsWith('.png')) {
                              fileName =
                                  'sticker_${DateTime.now().millisecondsSinceEpoch}.png';
                            } else {
                              fileName =
                                  'sticker_${DateTime.now().millisecondsSinceEpoch}.jpg';
                            }

                            final CroppedFile? croppedFile =
                                await ImageCropper().cropImage(
                              sourcePath: file.path,
                              uiSettings: [
                                AndroidUiSettings(
                                  toolbarTitle: '裁剪表情',
                                  toolbarColor: Colors.deepOrange,
                                  initAspectRatio:
                                      CropAspectRatioPreset.original,
                                  lockAspectRatio: false,
                                ),
                                IOSUiSettings(
                                  title: '裁剪表情',
                                ),
                              ],
                              compressFormat: file.path.endsWith('.png')
                                  ? ImageCompressFormat.png
                                  : ImageCompressFormat.jpg,
                            );
                            if (croppedFile?.path == null) {
                              return;
                            }

                            final file1 = File(croppedFile!.path);
                            var result =
                                await FlutterImageCompress.compressAndGetFile(
                              file1.absolute.path,
                              AppPath.resolveEmojiPath(fileName),
                              quality: 10,
                              format: file.path.endsWith('.png')
                                  ? CompressFormat.png
                                  : CompressFormat.jpeg,
                            );
                            if (result?.path == null) {
                              return;
                            }
                            await addSticker(result!.path, fileName);
                            await loadStickers();
                          }
                        }
                      },
                      id: 'sitcker',
                    ),
                  ];
                }
                return [];
              })
            : null,
        customStickerPanel:
            getPlatformType() == 'Mobile' ? _renderCustomStickerPanel : null,
        // New field, instead of `conversationID` / `conversationType` / `groupAtInfoList` / `conversationShowName` in previous.
        conversation: widget.selectedConversation,
        conversationShowName:
            customerServiceTyping ?? conversationName ?? _getTitle(),
        controller: _chatController,
        lifeCycle:
            ChatLifeCycle(newMessageWillMount: (V2TimMessage message) async {
          // ChannelPush.displayDefaultNotificationForMessage(message);
          return message;
        }, messageShouldMount: (V2TimMessage message) {
          return true;
        }, messageListShouldMount: (messageList) {
          List<V2TimMessage> list = [];
          for (V2TimMessage message in messageList) {
            CallingMessageDataProvider provide =
                CallingMessageDataProvider(message);
            if (!provide.isCallingSignal || !provide.excludeFromHistory) {
              list.add(message);
            }
          }
          return list;
        }),
        onDealWithGroupApplication: (String groupId) {
          if (!isWideScreen) {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => GroupApplicationList(
                  groupID: groupId,
                ),
              ),
            );
          } else {
            TUIKitWidePopup.showPopupWindow(
              operationKey: TUIKitWideModalOperationKey.addGroup,
              context: context,
              width: MediaQuery.of(context).size.width * 0.55,
              height: MediaQuery.of(context).size.width * 0.45,
              title: TIM_t("进群申请列表"),
              child: (closeFuncSendApplication) =>
                  TIMUIKitGroupApplicationList(groupID: groupID ?? ""),
            );
          }
        },
        groupAtInfoList: widget.selectedConversation.groupAtInfoList,
        showTotalUnReadCount: true,
        config: TIMUIKitChatConfig(
          stickerPanelConfig: StickerPanelConfig(
            useQQStickerPackage: true,
            useTencentCloudChatStickerPackage: true,
          ),
          onTapLink: PlatformUtils().isWeb
              ? (link) {
                  LinkUtils.launchURL(context,
                      "https://comm.qq.com/link_page/index.html?target=$link");
                }
              : null,
          showC2cMessageEditStatus: true,
          isAllowClickAvatar: true,
          isMemberCanAtAll: true,
          isAtWhenReply: false,
          isAtWhenReplyDynamic: (V2TimMessage message) {
            return false;
          },
          isAllowLongPressMessage: true,
          isShowReadingStatus: localSetting.isShowReadingStatus,
          isShowGroupReadingStatus: true,
          notificationTitle: "",
          isSupportMarkdownForTextMessage: false,
          urlPreviewType: UrlPreviewType.previewCardAndHyperlink,
          isUseMessageReaction: true,
          groupReadReceiptPermissionList: [
            GroupReceiptAllowType.work,
            GroupReceiptAllowType.meeting,
            GroupReceiptAllowType.public
          ],
          faceURIPrefix: (String path) {
            if (path.contains("assets/custom_face_resource/")) {
              return "";
            }
            int? dirNumber;
            if (path.contains("yz")) {
              dirNumber = 4350;
            }
            if (path.contains("ys")) {
              dirNumber = 4351;
            }
            if (path.contains("gcs")) {
              dirNumber = 4352;
            }
            if (dirNumber != null) {
              return "assets/custom_face_resource/$dirNumber/";
            } else {
              return "";
            }
          },
          faceURISuffix: (String path) {
            if (!path.contains("@2x.png")) {
              return "@2x.png";
            }
            return "";
          },
          additionalDesktopControlBarItems: [],
        ),
        conversationID: _getConvID() ?? '',
        conversationType:
            ConvType.values[widget.selectedConversation.type ?? 1],
        onTapAvatar: (userID, tapDetails) =>
            _onTapAvatar(userID, tapDetails, theme),
        initFindingMsg: widget.initFindingMsg,
        messageItemBuilder: MessageItemBuilder(
          messageRowBuilder: (message, messageWidget, onScrollToIndex,
              isNeedShowJumpStatus, clearJumpStatus, onScrollToIndexBegin) {
            if (MessageUtils.isGroupCallingMessage(message)) {
              // If group call message, not use default layout.
              return messageWidget;
            }
            if (MessageUtils.getCustomGroupCreatedOrDismissedString(message)
                .isNotEmpty) {
              return messageWidget;
            }
            return null;
          },
          customMessageItemBuilder: (message, isShowJump, clearJump) {
            return CustomMessageElem(
              message: message,
              isShowJump: isShowJump,
              clearJump: clearJump,
              chatController: _chatController,
            );
          },
        ),
        morePanelConfig: MorePanelConfig(
          showVideoCall: !isCustomerServiceChat,
          showVoiceCall: !isCustomerServiceChat,
          extraAction: [],
        ),
        appBarConfig: AppBar(
          actions: [
            Builder(builder: (BuildContext c) {
              return IconButton(
                  onPressed: () {
                    final conversationType = widget.selectedConversation.type;
                    if (conversationType == 1) {
                      _showTooltip(c);
                    } else {
                      final groupID = widget.selectedConversation.groupID;
                      if (groupID != null) {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => GroupProfilePage(
                              groupID: groupID,
                            ),
                          ),
                        );
                      }
                    }
                  },
                  icon: Icon(
                    Icons.more_horiz,
                    color: hexToColor("010000"),
                    size: 20,
                  ));
            })
            // IconButton(
            //     padding: const EdgeInsets.only(left: 8, right: 16),
            //     onPressed: () async {
            //       final conversationType = widget.selectedConversation.type;

            //       if (conversationType == 1) {
            //         _showTooltip(context);
            //         // final userID = widget.selectedConversation.userID;
            //         // // if had remark modified its will back new remark
            //         // String? newRemark = await Navigator.push(
            //         //     context,
            //         //     MaterialPageRoute(
            //         //       builder: (context) => UserProfile(
            //         //         userID: userID!,
            //         //         onRemarkUpdate: (String newRemark) {
            //         //           setState(() {
            //         //             conversationName = newRemark;
            //         //           });
            //         //         },
            //         //       ),
            //         //     ));
            //         // setState(() {
            //         //   backRemark = newRemark;
            //         // });
            //       } else {
            //         final groupID = widget.selectedConversation.groupID;
            //         if (groupID != null) {
            //           Navigator.push(
            //               context,
            //               MaterialPageRoute(
            //                 builder: (context) => GroupProfilePage(
            //                   groupID: groupID,
            //                 ),
            //               ));
            //         }
            //       }
            //     },
            //     icon: Icon(
            //       Icons.more_horiz,
            //       color: hexToColor("010000"),
            //       size: 20,
            //     ))
          ],
        ),
        customAppBar: isWideScreen
            ? ConstrainedBox(
                constraints: const BoxConstraints(maxHeight: 60),
                child: Stack(
                  children: [
                    Column(
                      children: [
                        Expanded(
                          child: TIMUIKitAppBar(
                            onClickTitle: (details) {
                              onClickUserName(
                                  Offset(details.globalPosition.dx,
                                      details.globalPosition.dy),
                                  theme);
                            },
                            config: AppBar(
                              backgroundColor: isWideScreen
                                  ? hexToColor("fafafa")
                                  : hexToColor("f2f3f5"),
                              actions: [
                                IconButton(
                                    padding: const EdgeInsets.only(
                                        left: 8, right: 16),
                                    onPressed: () async {
                                      onClickUserName(
                                          Offset(
                                              MediaQuery.of(context)
                                                      .size
                                                      .width -
                                                  380,
                                              30),
                                          theme);
                                    },
                                    icon: Icon(
                                      Icons.more_horiz,
                                      color: hexToColor("010000"),
                                      size: 20,
                                    ))
                              ],
                              // textTheme: TextTheme(
                              //     titleMedium: TextStyle(
                              //         color: hexToColor("010000"),
                              //         fontSize: 16)),
                            ),
                            conversationShowName: _getTitle(),
                            conversationID: _getConvID() ?? "",
                            showC2cMessageEditStatus: true,
                          ),
                        ),
                        SizedBox(
                          height: 1,
                          child: Container(
                            color: theme.weakDividerColor,
                          ),
                        ),
                      ],
                    ),
                    if (PlatformUtils().isMacOS)
                      SizedBox(
                        height: 20,
                        child: MoveWindow(),
                      ),
                  ],
                ))
            : null,
      ),
    );
  }
}
